import {
  registerDecorator,
  ValidationOptions,
  isNumber,
  isNumberString,
} from 'class-validator';

export function IsNumberOrNumberString(validationOptions?: ValidationOptions) {
  return function (object: Record<string, any>, propertyName: string) {
    registerDecorator({
      name: 'isNumberOrNumberString',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [],
      options: validationOptions,
      validator: {
        validate(value: any) {
          const res = isNumber(value) || isNumberString(value);
          return res;
          // you can return a Promise<boolean> here as well, if you want to make async validation
        },
      },
    });
  };
}

export function IsPhoneNumberCustom(validationOptions?: ValidationOptions) {
  return function (object: Record<string, any>, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: {
        validate(phone: any) {
          const phoneRegex = /^1\d{10}$/;
          return typeof phone === 'string' && phoneRegex.test(phone);
        },
        defaultMessage() {
          return '手机号格式不正确，必须为1开头的11位数字';
        },
      },
    });
  };
}
